'use strict';  
const mongoose = require('mongoose');  
const config = require('config');  
const { url } = config.get('Customer.mongodb_opt');  

class MongooseService {  
  constructor() {  
    // 简化的连接选项，因为许多选项现在是默认启用的  
  }  
  
  // 连接  
  async lift() {  
    try {  
      await mongoose.connect(url, this.options);  
      console.log('Mongoose connection open to ' + url);  
    } catch (err) {  
      console.error(`Mongoose connection open to ${url} error:`, err);  
    }  
  }  
  
  // 关闭  
  async lower() {  
    console.log(`MongoDB disconnect ${url}`);  
    try {  
      await mongoose.disconnect();  
      console.log('Mongoose connection disconnected');  
    } catch (err) {  
      console.error('Error disconnecting from MongoDB:', err);  
    }  
  }  
  
  // 使用事务 session commit abort  
  async useTrans(resolve) {  
    const session = await mongoose.startSession({  
      readPreference: { mode: 'primary' },  
      retryWrites: false, // 根据需要设置  
    });  
  
    session.startTransaction({  
      readConcern: { level: 'snapshot' },  
      writeConcern: { w: 'majority' },  
      readPreference: 'primary'  
    });  
  
    console.log("开启事务");  
  
    try {  
      const response = await resolve(  
        session,  
        async () => {  
          // 提交事务  
          await session.commitTransaction();  
        },  
        async () => {  
          // 回滚事务  
          await session.abortTransaction();  
        }  
      );  
      console.log("事务成功");  
      return response;  
    } catch (error) {  
      console.error("事务失败，回滚", error);  
      await session.abortTransaction();  
    } finally {  
      await session.endSession();  
      console.log("结束事务");  
    }  
  }  
}  
  
module.exports = new MongooseService();